package com.ochnas.examples.jsf.controller;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.ochnas.examples.jsf.domain.Bike;
import com.ochnas.examples.jsf.service.RentABike;
import com.ochnas.examples.jsf.ui.ApplicationService;

public class EditBikeController {
    private ApplicationService applicationService;
	private RentABike facade;
	private Bike bikeToEdit;

	/*
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if(request.getParameter("bikeSerialNo") == null) {
			System.out.println("bikeSerialNo was Null");
			return new ModelAndView("editBike.jsp");
		} else {
			System.out.println("bikeSerialNo == " + request.getParameter("bikeSerialNo"));
			Bike bike = facade.getBike(request.getParameter("bikeSerialNo"));
			return new ModelAndView("editBike.jsp", "bike", bike);
		} 
	} */
	
	public String editBike( ) {
//		HttpServletRequest request = (HttpServletRequest)
//									FacesContext.getCurrentInstance().getExternalContext().getRequest();
		
//		bikeToEdit = facade.getBike(request.getParameter("bikeSerialNo"));
		
		bikeToEdit = facade.getBike(applicationService.getRequestParameter("bikeSerialNo"));
		return "edit";
	}
	
	public String newBike() {
		bikeToEdit = new Bike();
		return "edit";
	}
	
	public String saveBike() {
		boolean isValid = true;
			if(bikeToEdit.getManufacturer() == null || "".equals(bikeToEdit.getManufacturer())){
				   applicationService.addErrorMessage("editForm:manufacturer","The manufacturer is required");
				   isValid = false;
			}
			if(bikeToEdit.getModel() == null || "".equals(bikeToEdit.getModel())){
				applicationService.addErrorMessage("editForm:model","The model is required");
				 isValid = false;
			}
			
		
		if (isValid)  {
			facade.saveBike(bikeToEdit);
		} else {
			return null;
		}
		return "bikes";
	}

	public RentABike getFacade() {
		return facade;
	}

	public void setFacade(RentABike facade) {
		this.facade = facade;
	}

	public Bike getBikeToEdit() {
		return bikeToEdit;
	}

	public void setBikeToEdit(Bike bikeToEdit) {
		this.bikeToEdit = bikeToEdit;
	}

	public ApplicationService getApplicationService() {
		return applicationService;
	}

	public void setApplicationService(ApplicationService applicationService) {
		this.applicationService = applicationService;
	}

}
